from copy import deepcopy
from .resnet import resnet50, resnet101

import torch
from torch import nn
import torch.nn.functional as F


class ASPPConv(nn.Sequential):
    def __init__(self, in_channels, out_channels, dilation):
        modules = [
            nn.Conv2d(in_channels, out_channels, 3, padding=dilation, dilation=dilation, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True)
        ]
        super(ASPPConv, self).__init__(*modules)


class ASPPPooling(nn.Sequential):
    def __init__(self, in_channels, out_channels):
        super(ASPPPooling, self).__init__(
            nn.AdaptiveAvgPool2d(1),
            nn.Conv2d(in_channels, out_channels, 1, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True))

    def forward(self, x):
        size = x.shape[-2:]
        x = super(ASPPPooling, self).forward(x)
        return F.interpolate(x, size=size, mode='bilinear', align_corners=False)


class ASPP(nn.Module):
    def __init__(self, in_channels, out_channels=256, atrous_rates=[6, 12, 18]):
        super(ASPP, self).__init__()
        modules = []
        modules.append(nn.Sequential(
            nn.Conv2d(in_channels, out_channels, 1, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True)))

        rate1, rate2, rate3 = tuple(atrous_rates)
        modules.append(ASPPConv(in_channels, out_channels, rate1))
        modules.append(ASPPConv(in_channels, out_channels, rate2))
        modules.append(ASPPConv(in_channels, out_channels, rate3))
        modules.append(ASPPPooling(in_channels, out_channels))

        self.convs = nn.ModuleList(modules)

        self.project = nn.Sequential(
            nn.Conv2d(5 * out_channels, out_channels, 1, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Dropout(0.1)
        )

    def forward(self, x):
        res = []
        for conv in self.convs:
            res.append(conv(x))
        res = torch.cat(res, dim=1)
        return self.project(res)


class Feature_Reweighting(nn.Module):

    # Ref: https://github.com/yiskw713/DualAttention_for_Segmentation/blob/master/model/attention.py

    def __init__(self):
        super(Feature_Reweighting, self).__init__()

        self.alpha = nn.Parameter(torch.zeros(1), requires_grad=True)   # Learnable Param.
        self.softmax = nn.Softmax(dim=-1)

    def forward(self, sup_fea, que_fea):
        """
        inputs :
            x : feature maps from feature extractor. (N, C, H, W)
        outputs :
            feature maps weighted by attention along a channel dimension
        """

        N, C, H, W = sup_fea.shape

        query_sup = sup_fea.reshape(N, C, -1)                  # (B, C, H*W)
        query_que = que_fea.reshape(N, C, -1)                  # (B, C, H*W)

        key_que = que_fea.reshape(N, C, -1).permute(0, 2, 1)  # (B, H*W, C)
        value_que = que_fea.reshape(N, C, -1)                  # (B, C, H*W)

        cross_atten = torch.bmm(query_sup, key_que)
        self_atten = torch.bmm(query_que, key_que)

        self_atten = torch.max(self_atten, -1, keepdim=True)[0].expand_as(self_atten) - self_atten  # prevent loss divergence https://github.com/junfu1115/DANet/issues/9
        cross_atten = torch.max(cross_atten, -1, keepdim=True)[0].expand_as(cross_atten) - cross_atten

        cross_atten_soft = self.softmax(cross_atten)  # (C, C)
        self_atten_soft = self.softmax(self_atten)    # (C, C)

        total_atten = (self_atten_soft + self.alpha*cross_atten_soft)/(1+self.alpha)

        out = torch.bmm(total_atten, value_que)
        out = out.view(N, C, H, W)
        out = out + que_fea

        return out


class Deeplabv3plusHead(nn.Module):
    def __init__(self, in_channels, low_level_channels, num_classes=1):
        super(Deeplabv3plusHead, self).__init__()

        self.aspp = ASPP(in_channels, 256, atrous_rates=[6, 12, 18])
        self.shortcut_conv = nn.Sequential(
            nn.Conv2d(low_level_channels, 48, kernel_size=(1, 1)),
            nn.BatchNorm2d(48),
            nn.ReLU(inplace=True)
        )

        self.cat_conv = nn.Sequential(
            nn.Conv2d(48 + 256, 256, kernel_size=(3, 3), stride=(1, 1), padding=1),
            nn.BatchNorm2d(256),
            nn.ReLU(inplace=True),
            nn.Dropout(0.1),
            nn.Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=1),
            nn.BatchNorm2d(256),
            nn.ReLU(inplace=True),
            nn.Dropout(0.1),
        )
        self.cls_conv = nn.Conv2d(256, num_classes, kernel_size=(1, 1), stride=(1, 1))

    def forward(self, x, query):

        x = self.aspp(x)
        query = self.shortcut_conv(query)
        #   将加强特征边上采样 与浅层特征堆叠后利用卷积进行特征提取
        x = F.interpolate(x, size=(query.size(2), query.size(3)), mode='bilinear',align_corners=True)
        x = self.cat_conv(torch.cat((x, query), dim=1))
        x = self.cls_conv(x)
        return x


# class Decoder(nn.Module):
#     def __init__(self, low_dim=256):
#         super(Decoder, self).__init__()
#         self.relu = nn.ReLU()
#         self.conv1 = nn.Conv2d(low_dim, 48, kernel_size=1, bias=False)
#         self.conv2 = nn.Conv2d(304, 256, kernel_size=3, padding=1, bias=False)

#     def forward(self, x, low_fea):
#         low_fea = self.conv1(low_fea)
#         low_fea = self.relu(low_fea)
#         x_4 = F.interpolate(x, size=low_fea.size()[2:4], mode='bilinear', align_corners=True)
#         x_4_cat = torch.cat((x_4, low_fea), dim=1)
#         x_4_cat = self.conv2(x_4_cat)
#         x_4_cat = self.relu(x_4_cat)
#         return x_4_cat


class Decoder(nn.Module):
    def __init__(self, output_channels, low_level_inplanes, BatchNorm=nn.BatchNorm2d):
        super(Decoder, self).__init__()

        self.conv1 = nn.Conv2d(low_level_inplanes, 48, 1, bias=False)
        self.bn1 = BatchNorm(48)
        self.relu = nn.ReLU()
        #channels should be 304
        self.last_conv = nn.Sequential(nn.Conv2d(304, 256, kernel_size=3, stride=1, padding=1, bias=False),
                                       BatchNorm(256),
                                       nn.ReLU(),
                                       nn.Dropout(0.5),
                                       nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=False),
                                       BatchNorm(256),
                                       nn.ReLU(),
                                       nn.Dropout(0.1),
                                       nn.Conv2d(256, output_channels, kernel_size=1, stride=1))
        self._init_weight()


    def forward(self, x, low_level_feat):
        low_level_feat = self.conv1(low_level_feat)
        low_level_feat = self.bn1(low_level_feat)
        low_level_feat = self.relu(low_level_feat)

        x = F.interpolate(x, size=low_level_feat.size()[2:], mode='bilinear', align_corners=True)
        x = torch.cat((x, low_level_feat), dim=1)
        x = self.last_conv(x)

        return x

    def _init_weight(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                torch.nn.init.kaiming_normal_(m.weight)
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

class Attention(nn.Module):
    def __init__(self, dim, num_heads=8, head_dim_ratio=1., attn_drop=0., proj_drop=0.):
        super().__init__()
        self.dim = dim
        self.num_heads = num_heads
        head_dim = round(dim // num_heads * head_dim_ratio)
        self.head_dim = head_dim
        self.scale = head_dim ** -0.5
        self.qk = nn.Conv2d(dim, head_dim * num_heads * 2, 1, stride=1, padding=0, bias=False)
        self.v = nn.Conv2d(dim, head_dim * num_heads, 1, stride=1, padding=0, bias=False)
        self.attn_drop = nn.Dropout(attn_drop)
        self.proj = nn.Conv2d(self.head_dim * self.num_heads, dim, 1, stride=1, padding=0, bias=False)
        self.proj_drop = nn.Dropout(proj_drop)

    def forward(self, x, query):
        B, C, H, W = x.shape
        x = self.qk(x).reshape(B, 2, self.num_heads, self.head_dim, -1).permute(1, 0, 2, 4, 3)
        q, k = x.unbind(0)

        v = self.v(query).reshape(B, self.num_heads, self.head_dim, -1).permute(0, 1, 3, 2)

        attn = (q @ k.transpose(-2, -1)) * self.scale
        attn = attn.softmax(dim=-1)
        attn = self.attn_drop(attn)
        x = attn @ v

        x = x.permute(0, 1, 3, 2).reshape(B, -1, H, W)
        x = self.proj(x)
        x = self.proj_drop(x) + query
        return x


class CPMT(nn.Module):
    def __init__(self, backbone, shot=1, pretrained=True):
        super(CPMT, self).__init__()
        backbone = eval(backbone)(pretrained=pretrained)  # 创建backbone
        self.layer0 = nn.Sequential(backbone.conv1, backbone.bn1, backbone.relu, backbone.maxpool)
        self.layer1, self.layer2, self.layer3, self.layer4 = backbone.layer1, backbone.layer2, backbone.layer3, backbone.layer4
        self.shot = shot
        self.temperature=0.07
        self.res = nn.Sequential(
            nn.Conv2d(2049, 1024, kernel_size=1, padding=0, bias=False),
            nn.BatchNorm2d(1024),
            nn.ReLU(inplace=True),
            nn.Conv2d(1024, 256, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(256),
            nn.ReLU(inplace=True)               
        )              

        self.decoder = Deeplabv3plusHead(in_channels=256,low_level_channels=1024,num_classes=2)


    
    # def ema(self, alpha, global_step):
    #     alpha = min(1 - 1 / (global_step + 1), alpha)
    #     for ema_param, param in zip(self.teacher_project_head.parameters(), self.project_head.parameters()):
    #         ema_param.data.mul_(alpha).add_(param.data, alpha=1 - alpha)

    def forward(self, img_s_list, mask_s_list, img_q, mask_q):
        """
        img_s_list: List
        mask_s_list: List
        img_q:[batch_size,3,473,473]
        mask_q:[batch_size,473,473]

        """
        h, w = img_q.shape[-2:]

        # feature maps of support images
        supp_list_mid = []
        supp_list_high = []
        mask_list = []

        #  获取支持集的特征
        for k in range(len(img_s_list)):
            mask = (mask_s_list[k] == 1).float().unsqueeze(1)
            mask_list.append(mask)

            with torch.no_grad():
                s_0 = self.layer0(img_s_list[k])  # [4,128,119,119]
                s_1 = self.layer1(s_0)  # [4,128,119,119] -> [4,256,119,119]

            s_2 = self.layer2(s_1)  # [4,256,119,119] -> [4,512,60,60]
            s_3 = self.layer3(s_2)  # [4,512,60,60]   -> [4,1024,60,60]
            # s_4 = self.layer4(s_3)  # [4,1024,60,60]  -> [4,2048,60,60]

            # supp_feat = torch.cat([s_2, s_3], 1)  # [4,512,60,60] + [4,1024,60,60] =[4,1536,60,60]
            # supp_feat = self.down_supp(supp_feat)  # [4,256,60,60]

            supp_list_mid.append(s_3)  # 对中级语义特征进行处理
            # supp_list_high.append(s_4)  # 添加高级语义特征

        # 获取查询集图像的特征
        with torch.no_grad():
            q_0 = self.layer0(img_q)
            q_1 = self.layer1(q_0)

        q_2 = self.layer2(q_1)
        q_3 = self.layer3(q_2)  # [4,1024,60,60]

        """
        supp_feat_list: 支持集对应的中级语义特征的原型 shot x [batch_size,256,60,60]
        final_supp_list : 支持集对应的高级语义特征 shot x [batch_size,2048,60,60]
        query_feat: 查询集的中级语义特征 [batch_size,256,60,60]
        final_query_feat: 查询集的中级语义特征 [batch_size,2048,60,60]
        """



       

        # foreground(target class) and background prototypes pooled from K support features
        feature_fg_list = []
        feature_bg_list = []
        supp_out_ls = []
        for k in range(len(img_s_list)):
            # feature_fg=[1,4,1024]
            feature_fg = self.masked_average_pooling(supp_list_mid[k], (mask_s_list[k] == 1).float())[None, :]
            # feature_bg=[1,4,1024]
            feature_bg = self.masked_average_pooling(supp_list_mid[k], (mask_s_list[k] == 0).float())[None, :]
            feature_fg_list.append(feature_fg)
            feature_bg_list.append(feature_bg)

        # 对shot个图片进行平均，计算原型 [4,1024,1,1]
        FP = torch.mean(torch.cat(feature_fg_list, dim=0), dim=0).unsqueeze(-1).unsqueeze(-1)
        # 背景原型 [4,1024,1,1]
        BP = torch.mean(torch.cat(feature_bg_list, dim=0), dim=0).unsqueeze(-1).unsqueeze(-1)

        supp_feat_bin = FP.expand(-1, -1, 60, 60)
        corr_query_mask = self.generate_prior(supp_list_mid, mask_s_list, q_3)
        query_feat =torch.cat([supp_feat_bin, corr_query_mask, q_3],dim=1)
        query_feat = self.res(query_feat) 
        out_1 = self.decoder(query_feat,q_3)
        out_1 = F.interpolate(out_1, size=(h, w), mode="bilinear", align_corners=True)  # [4,2,473,473]

        # 计算查询特征和前景和背景的原型 之间的相似度。计算出初步的分割掩码
        out_0 = self.similarity_func(q_3, FP, BP)  # [4,2,60,60]
        out_0 = F.interpolate(out_0, size=(h, w), mode="bilinear", align_corners=True)  # [4,2,473,473]


        if self.training:
            out_ls = []
            # 通过 查询集的输出的特征，根据掩码，输出查询集的前景和背景的原型
            fg_q = self.masked_average_pooling(q_3, (mask_q == 1).float())[None, :].squeeze(0)  # [4,1024]
            bg_q = self.masked_average_pooling(q_3, (mask_q == 0).float())[None, :].squeeze(0)  # [4,1024]

            # logit, label =self.InfoNCE_logits(FP.squeeze(-1).squeeze(-1),fg_q,bg_q)
            # with torch.no_grad():
            #     query_FP = self.teacher_project_head(fg_q.detach())  # [4,128]
            #     query_BP = self.teacher_project_head(bg_q.detach())  # [4,128]

            for i in range(self.shot):
                # 根据查询集的原型，计算出支持集的分割图
                self_out = self.similarity_func(supp_list_mid[i], fg_q[..., None, None], bg_q[..., None, None])
                self_out = F.interpolate(self_out, size=(h, w), mode="bilinear", align_corners=True)
                out_ls.append(self_out)

            return out_0, out_ls,out_1

        return out_0, out_1
    
    def InfoNCE_logits(self, f_q, f_k,f_mem):
        '''
        Compute the similarity logits between positive samples and positve to all negatives in the memory.
        计算记忆中正样本和正样本与所有负样本之间的相似度逻辑。
        args:
            f_q (Tensor): Feature reprentations of the view x_q computed by the query_encoder.
            f_k (Tensor): Feature reprentations of the view x_k computed by the key_encoder.
        returns:
            logit (Tensor): Positve and negative logits computed as by InfoNCE loss. (bsz, queue_size + 1)
            label (Tensor): Labels of the positve and negative logits to be used in softmax cross entropy. (bsz, 1)
        '''
        f_k = f_k.detach()
        f_mem = f_mem.clone().detach()  # Get queue from register_buffer
        # Normalize the feature representations
        f_q = nn.functional.normalize(f_q, dim=1)
        f_k = nn.functional.normalize(f_k, dim=1)
        f_mem = nn.functional.normalize(f_mem, dim=1)

        # Compute sim between positive views.计算两者之间的相似度
        pos = torch.bmm(f_q.view(f_q.size(0), 1, -1),f_k.view(f_k.size(0), -1, 1)).squeeze(-1)
        # Compute sim between postive and all negatives in the memory
        neg = torch.mm(f_q, f_mem.transpose(1, 0))
        logits = torch.cat((pos, neg), dim=1)
        logits /= self.temperature
        # Create labels, first logit is postive, all others are negative
        labels = torch.zeros(logits.shape[0],dtype=torch.long).cuda()  

        return logits, labels

    def similarity_func(self, feature_q, fg_proto, bg_proto):
        """
         通过计算相似度来进行分割
         feature_q: [4,1024,60,60] 查询集特征
         fg_proto: [4,1024,1,1] 前景原型
         bg_proto: [4,1024,1,1] 背景原型
         结果: [4,2,60,60] 初步的分割结果
        """

        similarity_fg = F.cosine_similarity(feature_q, fg_proto, dim=1)
        similarity_bg = F.cosine_similarity(feature_q, bg_proto, dim=1)

        out = torch.cat((similarity_bg[:, None, ...], similarity_fg[:, None, ...]), dim=1) * 10.0  # [4,2,60,60]
        return out

    def masked_average_pooling(self, feature, mask):
        """
        通过mask_pool操作获取对应特征的原型。
        feature: [4,1024,60,60]
        mask:  [4,473,473]
        return feature #[4,1024]
        """
        mask = F.interpolate(mask.unsqueeze(1), size=feature.shape[-2:], mode='bilinear', align_corners=True)
        masked_feature = torch.sum(feature * mask, dim=(2, 3)) / (mask.sum(dim=(2, 3)) + 1e-5)
        return masked_feature

        
    
    def generate_prior(self, final_supp_list, mask_list, query_feat):

        corr_query_mask_list = []
        cosine_eps = 1e-7

        for i, tmp_supp_feat in enumerate(final_supp_list):  # 这个就是掩码后的特征 # [4,2048,60,60]

            mask = mask_list[i].float().unsqueeze(1)
            tmp_mask = F.interpolate(mask, size=tmp_supp_feat.shape[-2:],mode='bilinear', align_corners=True)  # [4,1,60,60]

            tmp_supp_feat_4 = tmp_supp_feat * tmp_mask  # [4,2048,60,60]    掩码后支持集的高级语义特征
            q = query_feat  # [4,2048,60,60] # 查询集的高级语义特征
            s = tmp_supp_feat_4  # [4,2048,60,60] 支持集的高级语义特征
            bsize, ch_sz, qh, qw = q.size()[:]  # [4,2048,60]

            tmp_query = q
            tmp_query = tmp_query.contiguous().view(bsize, ch_sz, -1)  # [4,2048,3600]
            tmp_query_norm = torch.norm(tmp_query, 2, 1, True)  # [4,1,3600] # 查询集特征进行归一化。意思就是每个像素的归一化的值

            tmp_supp = s      # [4,2048,60,60] #
            tmp_supp = tmp_supp.contiguous().view(bsize, ch_sz, -1)  # [4,2048,3600]
            tmp_supp = tmp_supp.contiguous().permute(0, 2, 1)  # [4,3600,2048,]
            tmp_supp_norm = torch.norm(tmp_supp, 2, 2, True)  # [4,3600,1,] # 支持集的特征进行归一化，意思就是每个像素的归一化的值

            similarity = torch.bmm(tmp_supp, tmp_query)/(torch.bmm(tmp_supp_norm, tmp_query_norm) + cosine_eps)  # [4,3600,3600] 计算相似度
            similarity = similarity.max(1)[0].view(bsize, qh*qw)   # [4,3600] 取相似度中最高的那个
            similarity = (similarity - similarity.min(1)[0].unsqueeze(1)) / (similarity.max(1)[0].unsqueeze(1) - similarity.min(1)[0].unsqueeze(1) + cosine_eps)  # [4,3600] 对相似度进行归一化
            corr_query = similarity.view(bsize, 1, qh, qw)  # [4,1,60,60] 重新resize成 图片大小
            corr_query = F.interpolate(corr_query, size=(query_feat.size()[2], query_feat.size()[3]),mode='bilinear', align_corners=True)  # [4,1,60,60]
            corr_query_mask_list.append(corr_query)  # 完成这个batch的计算。添加

         # List = shot * [batch_size,1,h,w]  5 x [4,1,60,60]
        corr_query_mask = torch.cat(corr_query_mask_list, 1).mean(1).unsqueeze(1)   # shot * [batch_size,1,h,w] -> [shot x batchsize,1,60,60]
        # 对所有图片进行放大
        corr_query_mask = F.interpolate(corr_query_mask, size=(query_feat.size(2), query_feat.size(3)),mode='bilinear', align_corners=True)  

        return corr_query_mask
